<template>
  <q-page padding>
    <mini-table
      class="sticky-last-column-table"
      :rows="rows"
      :columns="columns"
      :loading="loading"
      row-key="id"
      v-model:selected="mySelection"
    >
      <!-- 表头 -->
      <template #top-left>
        <div class="row q-gutter-x-sm">
          <q-btn icon="add" dense outline label="新增" @click="operatorBtn('add', formData)" />
          <q-btn
            icon="delete"
            :disable="mySelection.length == 0"
            dense
            outline
            label="批量删除"
            @click="batchDeleteIds"
          />
          <q-btn icon="refresh" dense outline @click="refresh" :loading="loading" label="刷新" />
        </div>
      </template>
      <!-- 相关列 -->
      <template v-slot:body-cell-user_gender="{ row }">
        <q-td>
          <q-badge
            :color="row.user_gender === '1' ? 'primary' : 'purple'"
            :label="row.user_gender === '1' ? '男' : '女'"
          />
        </q-td>
      </template>
      <template v-slot:body-cell-status="{ row }">
        <q-td>
          <q-badge
            :color="row.status ? 'primary' : 'purple'"
            :label="row.status ? '启用' : '禁用'"
          />
        </q-td>
      </template>
      <template v-slot:body-cell-operator="props">
        <q-td>
          <q-btn dense icon="edit" outline class="mr-5px" @click="operatorBtn('edit', props.row)" />
          <q-btn
            dense
            icon="delete"
            :loading="loading"
            outline
            @click="handelDelete([props.key])"
          />
        </q-td>
      </template>
    </mini-table>
  </q-page>
  <add-dialog-page
    v-model:dialog="addDialog"
    v-model:formData="formData"
    @success="refresh"
    v-model:isEdit="isEdit"
    v-model:currentId="currentId"
  />
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import MiniTable from 'src/components/common/MiniTable/index.vue'
import addDialogPage from 'src/pages/manage/user/addDialogPage.vue'
import { getUserList, deleteBatchUser } from 'src/api/methods/user'
import { useRequest } from 'alova/client'
import { useDataReset } from 'src/hooks/useReset'
import { useQuasar } from 'quasar'
import type { QTableColumn } from 'quasar'
import type { RoleList, UserIn, UserListOut } from 'src/api/globals'
import { invalidateCache } from 'alova'

defineOptions({
  name: 'UserPage',
})

const $q = useQuasar()

const {
  loading,
  data: rows,
  send,
} = useRequest(getUserList(), {
  initialData: [],
})

const userFormData: UserIn = {
  user_no: '',
  user_name: '',
  password: '666',
  nick_name: '',
  user_email: '',
  user_gender: '1',
  user_phone: '',
  role_list: [] as RoleList[],
  status: true,
}

// 添加 formData
const { copy: initFormData, dataReset } = useDataReset(userFormData)

const addDialog = ref<boolean>(false)
const formData = ref<UserIn>(initFormData.value)

// 选择项
const mySelection = ref<UserListOut[]>([])

// 添加或编辑
const isEdit = ref(false)

// 当前行ID
const currentId = ref<number>(-1)

watch(
  () => addDialog.value,
  (val) => {
    if (!val) isEdit.value = false
  },
)

// 新增或编辑按钮
const operatorBtn = (o_type: 'add' | 'edit', data: UserListOut | UserIn) => {
  if (o_type === 'add') {
    // 重置表单
    dataReset()
    formData.value = initFormData.value
  } else {
    console.log('row::::', data)
    formData.value = {
      user_no: data.user_no,
      user_name: data.user_name,
      nick_name: data.nick_name,
      user_email: data.user_email,
      user_gender: data.user_gender,
      user_phone: data.user_phone,
      role_list: data.role_list as RoleList[],
      status: data.status as boolean,
    }
    currentId.value = (data as UserListOut).id // 类型断言
    isEdit.value = true
  }
  addDialog.value = !addDialog.value
}

const columns: QTableColumn[] = [
  {
    name: 'user_no',
    label: '编号',
    field: 'user_no',
    align: 'left',
    sortable: true,
  },
  {
    name: 'user_name',
    label: '名称',
    field: 'user_name',
    align: 'left',
  },
  {
    name: 'nick_name',
    label: '昵称',
    field: 'nick_name',
    align: 'left',
  },
  {
    name: 'user_gender',
    label: '性别',
    field: 'user_gender',
    format: (val) => (val == '1' ? '男' : '女'),
    align: 'left',
  },
  {
    name: 'user_email',
    label: '邮箱',
    field: 'user_email',
    align: 'left',
  },
  {
    name: 'user_phone',
    label: '手机',
    field: 'user_phone',
    align: 'left',
  },
  {
    name: 'status',
    label: '状态',
    field: 'status',
    format: (val) => (val ? '启用' : '禁用'),
    align: 'left',
  },
  {
    name: 'create_time',
    label: '创建时间',
    field: 'create_time',
    align: 'left',
  },
  {
    name: 'update_time',
    label: '更新时间',
    field: 'update_time',
    align: 'left',
  },
  {
    name: 'operator',
    label: '操作',
    field: 'operator',
    align: 'left',
  },
]

// 刷新
const refresh = () => {
  invalidateCache(getUserList()).catch((err) => alert('请求错误' + err))
  loading.value = true
  send()
    .catch((err) => $q.notify('请求错误' + err))
    .finally(() => (loading.value = false))
}

// 删除用户(支持批量)
const handelDelete = (ids: number[]) => {
  $q.dialog({
    title: '删除提示',
    message: `确定删除吗？`,
    ok: '确认',
    cancel: '取消',
  }).onOk(() => {
    deleteBatchUser(ids)
      .then(() => {
        $q.notify('删除成功')
        refresh()
      })
      .catch((err) => $q.notify({ message: err }))
  })
}

// 批量删除
const batchDeleteIds = () => {
  const ids = mySelection.value.map((item) => item.id)
  handelDelete(ids)
}
</script>
